package com.xing.book.test;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;


public class MyDbPool implements DataSource {

    //创建一个集合
    private static CopyOnWriteArrayList<Connection> arrayList=new CopyOnWriteArrayList<>();
    static {
        try {
            Properties properties = new Properties();
            InputStream is = MyDbPool.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(is);
            is.close();
            String url= properties.getProperty("url");
            String user= properties.getProperty("user");
            String password=properties.getProperty("password");
            for (int i = 0; i < 5; i++) {
                Connection connection = DriverManager.getConnection(url, user, password);
                arrayList.add(connection);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    @Override
    public Connection getConnection() throws SQLException {
        if(arrayList.size()>0){
            return arrayList.remove(0);
        }
        return null;
    }
    //归还连接
    public void release(Connection connection){
        arrayList.add(connection);
    }


    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
